<template>
  <div class="my">
    <Header
      hide-btn
      title="我的"
    />
    <div class="my-container">
      <div class="my-info">
        <div
          @tap="updateHeader"
          v-html="myInfo.photo"
          class="headerImg"
        />
        <p class="my-info-name">
          {{ myInfo.username || '暂无' }}
        </p>
        <p class="my-info-phone">
          {{ myInfo.userCode || '暂无' }}
        </p>
        <p class="my-info-email">
          {{ myInfo.businessEmail || '暂无' }}
        </p>
        <p class="my-info-company">
          {{ myInfo.jtgsMc || '暂无' }}
        </p>
      </div>

      <!-- <div
        v-show="QUICKLOGIN=='1' && (isApplicationExist('weixin') || isApplicationExist('weixin'))"
        class="my-account-binding"
      >
        <div
          v-if="isApplicationExist('weixin')"
          class="binding-content je-audio-btn"
        >
          <span>微信号绑定</span>
          <div @tap="goCancel(1,weixinBinding)">
            <img
              v-show="weixinBinding"
              src="./assets/weixin-binded.png"
            >
            <a :class="[weixinBinding?'enable':'']">{{ !weixinBinding?'未启用':weixinBinding }}</a>
            <i class="jeicon jeicon-angle-right" />
          </div>
        </div>
        <div
          v-if="isApplicationExist('qq')"
          class="binding-content je-audio-btn"
        >
          <span>QQ绑定</span>
          <div @tap="goCancel(2,qqBinding)">
            <img
              v-show="qqBinding"
              src="./assets/qq-binged.png"
            >
            <a :class="[qqBinding?'enable':'']">{{ !qqBinding?'未启用':qqBinding }}</a>
            <i class="jeicon jeicon-angle-right" />
          </div>
        </div>
      </div> -->
      <div class="my-account-binding my-setting">
        <div
          @tap="handleResetPassword"
          class="binding-content je-audio-btn"
        >
          <span>修改密码</span>
          <div>
            <i class="jeicon jeicon-angle-right" />
          </div>
        </div>
        <div class="binding-content">
          <span>按钮音效</span>
          <div>
            <input
              v-model="hasVadio"
              class="my-switch my-switch-anim"
              type="checkbox"
            >
          </div>
        </div>
        <div class="binding-content">
          <span>手机版本</span>
          <div>
            <a class="version">版本 {{ version }}</a>
          </div>
        </div>
      </div>

      <div class="my-footer">
        <button
          @tap="logout"
          class="my-logout je-audio-btn"
        >
          退出
        </button>
      </div>
    </div>
    <ImgCroper
      :picValue="picValue"
      :showCroper="showCroper"
      @upImg="doupload"
      @hideClip="hideClip"
    />
  </div>
</template>
<script>
import {
  openWindow, capture, pick, isApplicationExist,
} from '@/helper';
import {
  fetchCreateState,
  fetchOtherLogin,
  fetchUserMess,
  uploaderImg,
  saveUserImg,
} from './actions/my';
import Header from '@/components/header';
import ImgCroper from '@/components/imgCroper';

export default {
  name: 'My',
  components: {
    Header,
    ImgCroper,
  },
  data() {
    return {
      myInfo: {
        phone: '',
        jtgsMc: '',
        avatar: '',
        username: '',
        businessEmail: '',
      },
      weixinBinding: '',
      qqBinding: '',
      dingdingBinding: '',
      auths: [],
      version: '',
      hasVadio: '',
      picValue: '', // 选择完照片后的路径
      showCroper: false,
      QUICKLOGIN: '1',
    };
  },
  watch: {
    hasVadio: {
      handler(newVal) {
        if (typeof (newVal) === 'boolean') {
          JE.setLSItem('_audio_button', newVal ? '1' : '0');
        }
      },
      immediate: true,
    },
  },
  created() {
    if (!JE.getLSItem('_audio_button')) {
      JE.setLSItem('_audio_button', '0');
    } else {
      this.hasVadio = JE.getLSItem('_audio_button') !== '0';
    }
    mui.back = () => {
      plus.webview.getLaunchWebview().evalJS('mui.back();');
    };
    this.version = JE.getVersion('inner');
    Waves.init();
  },
  mounted() {
    this.QUICKLOGIN = JE.getSystemConfig().JE_SYS_QUICKLOGIN;
    window.addEventListener('backParent', () => {
      window.location.reload();
    });

    mui.plusReady(() => {
      plus.oauth.getServices(
        (services) => {
          this.auths = services;
        //   for ( var i in this.auths ) {
        //   var s = this.auths[i];
        //   if ( s.authResult ) {
        //     s.logout(function(e){
        //       console.log( "注销登录认证成功！" );
        //     }, function(e){
        //       console.log( "注销登录认证失败！" );
        //     });
        //   }
        // }
        },
        () => {},
      );
    });
    this.myInfo = JE.getCurrentUser();
    if (this.myInfo) {
      this.myInfo.photo = JE.getUserPhoto(this.myInfo.id, true);
    }
    this.getBind();
  },
  methods: {
    isApplicationExist,
    // showAPPenter(app){
    //   if(!isApplicationExist){
    //     mui.toast('请先登录此软件')
    //   }
    // },
    async getBind() {
      const getUserBind = await fetchUserMess({ userId: this.myInfo.id });
      if (getUserBind.success) {
        this.qqBinding = getUserBind.obj.AT_QQ_NAME;
        this.weixinBinding = getUserBind.obj.AT_WX_NAME;
      } else {
        this.qqBinding = '';
        this.weixinBinding = '';
      }
    },
    // 更换头像
    updateHeader() {
      if (!window.plus) {
        return false;
      }

      const that = this;
      plus.nativeUI.actionSheet(
        {
          cancel: '取消',
          buttons: [{ title: '相机' }, { title: '相册' }],
        },
        ({ index }) => {
          switch (index) {
            case 1:
              capture().then((result) => {
                that.handleFile(result);
              }).catch(() => {
                // mui.toast(JSON.stringify(e));
              });
              break;
            case 2:
              pick().then(([result]) => {
                that.handleFile(result);
              }).catch(() => {
              });
              break;
            default:
              break;
          }
        },
      );
    },
    // 将图片转换为 Base64
    handleFile(path) {
      const that = this;
      return new Promise((resolve, reject) => {
        plus.zip.compressImage({
          src: path,
          dst: `_doc/temp/${+new Date()}.jpg`,
          quality: 70,
        },
        ({ target }) => {
          plus.io.resolveLocalFileSystemURL(target, (file) => {
            const fileReader = new plus.io.FileReader();
            fileReader.readAsDataURL(file);
            fileReader.onloadend = ({ target: { result } }) => {
              that.picValue = result;
              that.showCroper = true;
              resolve(result);
            };
          });
        },
        (e) => {
          reject(e);
        });
      });
    },
    // 上传头X
    async doupload(url) {
      const { success, message, obj } = await uploaderImg({
        data: url,
        tableCode: 'JE_CORE_ENDUSER',
        beanTableCode: 'JE_CORE_ENDUSER',
        jeFileType: 'PROJECT',
        pkValue: JE.getCurrentUser().id,
        funcCode: 'JE_CORE_ENDUSER',
        fieldCode: 'PHOTO',
        fileFormat: 'image/jpeg',
        fileName: '1.jpg',
      });
      if (success) {
        this.showCroper = false;
        this.myInfo.photo = `<img class="je-user-photo photo-img" src="${JE.getFileUrl(obj[0].fileKey, 'preview')}">`;
        JE.getCurrentUser().photo = `<img class="je-user-photo photo-img" src="${JE.getFileUrl(obj[0].fileKey, 'preview')}">`;
        // JE.setCurrentUser(JE.getCurrentUser());
        // let { photo } = JE.getUsers(JE.getCurrentUser().userId);
        // photo = photo.split('*');
        // photo[1] = JE.getFileUrl(obj[0].fileKey, 'preview');// obj.DOCUMENT_PRIVATEKEY.substr(obj.DOCUMENT_PRIVATEKEY.indexOf('.com') + 4);
        // JE.getUsers(JE.getCurrentUser().userId).photo = photo.join('*');
        // JE.getUsers(JE.getCurrentUser().userId).photoUrl = JE.getFileUrl(obj[0].fileKey, 'preview');
        // JE.setUsers(JE.getUsers(JE.getCurrentUser().userId));
        await saveUserImg({
          tableCode: 'JE_CORE_ENDUSER',
          USERID: JE.getCurrentUser().userId,
          PHOTO: `${obj[0].relName}*${obj[0].fileKey}`,
        });
      } else {
        mui.toast(message);
      }
    },
    hideClip() {
      this.showCroper = false;
    },
    // 第三方绑定
    async goCancel(type, val) {
      // 发起状态机
      if (!isApplicationExist(type == '1' ? 'weixin' : 'qq')) {
        mui.toast('请先登录此app');
        return;
      }
      const typeArr = ['WX', 'QQ', 'DT'];
      const stateRes = await fetchCreateState({
        type: 'PC',
        loginType: typeArr[type - 1],
      });
      // 调起三方
      if (val) {
        openWindow({
          url: './pages_cancel_index.html',
          id: '__cancelView',
          title: '',
          extras: { type },
        });
        // this.$router.push({ name: 'my_cancel', params: { type } });
      } else {
        switch (type) {
          case 1:
            this.authLogin('weixin', stateRes);
            break;
          case 2:
            this.authLogin('qq', stateRes);
            break;
          default:
            break;
        }
      }
    },
    // 退出登录
    logout() {
      if(window.plus){
        plus.runtime.quit();
      }else{
        JE.logout();
        Waves.attach('.my-logout', ['waves-button', 'waves-float']);
      }
    },
    // 第三方绑定
    async authLogin(type, stateRes) {
      let s;
      let a;
      for (let i = 0; i < this.auths.length; i++) {
        if (this.auths[i].id == type) {
          s = this.auths[i];
          break;
        }
      }
      if (!s.authResult) {
        s.login(() => {
          // a = e;
          s.getUserInfo(async (e) => {
            a = e;// 在这里拿到了openid 和tooken
            const userInfo = a.target;
            let onlyId;
            if (type == 'qq') {
              onlyId = userInfo.authResult.openid;
            }
            if (type == 'weixin') {
              onlyId = userInfo.authResult.unionid;
            }
            const dingTalkPersistent = await fetchOtherLogin({
              openId: onlyId, // 临时授权码
              state: stateRes.obj.STATE,
              nick: userInfo.userInfo.nickname,

            });
            if (dingTalkPersistent.success) {
              if (type == 'qq') {
                this.qqBinding = userInfo.userInfo.nickname;
              }
              if (type == 'weixin') {
                this.weixinBinding = userInfo.userInfo.nickname;
              }
              s.logout();
            } else {
              mui.toast('授权绑定失败');
            }
          });
        });
      } else {
        console.log(s.authResult);
        // mui.toast('授权绑定失败');
      }
    },
    handleResetPassword() {
      window.plus ? openWindow({
        url: './pages_modifyPsd_index.html',
        id: '__modifyPsdView',
        title: '重置密码',
        hideNView: true,
        extras: {
          phone: this.myInfo.userCode,
          deptId: this.myInfo.deptId,
          online: true,
        },
        style: {
          top: 0,
          bottom: 0,
        },
      }) : this.$router.push({
        path: '/JE-PLUGIN-MY/modifyPsd',
        query: {
          phone: this.myInfo.userCode,
          deptId: this.myInfo.deptId,
          online: true,
        },
      });
    },
  },
};
</script>
<style lang="less">
  img {
    width: 100%;
  }
</style>
<style lang="less" scoped>
  @import '~@/theme/index.less';
  header.je-header{
    background-color: transparent;
  }
  .my {
    background: url("./assets/bg.png") no-repeat top center fixed;
    background-size: 100% 602px;
    height: 100%;
    width: 100%;
    background-color: #f2f2f2;

    .my-container {
      width: 100%;
      position: absolute;
      // overflow-x: hidden;
      // overflow-y: auto;
      top: 45 * @hd;
      -webkit-overflow-scrolling: touch;

      .my-info {
        // padding-top: 130px;
        text-align: center;
        height: 360px;
        .headerImg {
          width: 120px;
          height: 120px;
          display: inline-block;
          background-color: #FFA03E;
          color: #fff;
          text-align: center;
          line-height: 125px;
          font-size: 32px;
          border-radius: 60px;
          overflow: hidden;
        }
        .my-info-name {
          margin-top: 20px;
          font-size: 36px;
          font-weight: 500;
          color: #ffffff;
        }
        .my-info-phone,
        .my-info-email,
        .my-info-company {
          font-size: 24px;
          padding: 1 * @hd 0;
          color: #ffffff;
        }
      }
      .my-account-binding,
      .my-setting {
        background: #ffffff;
        margin: 10 * @hd 30px 0 30px;
        border-radius: 12px;
        padding: 0 36px 40px 44px;
        .binding-content {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding-top: 36px;
          span {
            font-size: 32px;
            color: #444444;
          }
          div {
            display: flex;
            align-items: center;
            justify-content: center;
            img {
              width: 26px;
              height: 26px;
            }
            i {
              color: #a9aba9;
              font-size: 20px;
            }
            a {
              margin-left: 5px;
              margin-right: 24px;
              font-size: 24px;
              color: #a9aba9;
            }
            .enable {
              color: #5a5a5a;
            }
            .version {
              margin-right: 0;
            }
          }
        }
      }

      .my-footer {
        width: 100%;
        padding: 54*@hd 76px 0 74px;
        .my-logout {
          height: 96px;
          background: #536dfe;
          box-shadow: 0 5px 14px 0 rgba(83, 109, 254, 0.44);
          border-radius: 16px;
          font-size: 36px;
          color: #ffffff;
          width: 100%;
        }
      }
    }

  }

  .my-switch {
    width: 68px;
    height: 40px;
    position: relative;
    border: 1px solid #dfdfdf;
    background-color: #fdfdfd;
    box-shadow: #dfdfdf 0 0 0 0 inset;
    border-radius: 25px;
    background-clip: content-box;
    display: inline-block;
    -webkit-appearance: none;
    user-select: none;
    outline: none;
  }

  .my-switch:before {
    content: "";
    width: 35px;
    height: 34px;
    position: absolute;
    top: 0px;
    left: 0;
    border-radius: 34px;
    background-color: #fff;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.4);
  }

  .my-switch:checked {
    border-color: #4bd763;
    box-shadow: #4bd763 0 0 0 16px inset;
    background-color: #4bd763;
  }

  .my-switch:checked:before {
    left: 28px;
  }

  .my-switch.my-switch-animbg {
    transition: background-color ease 0.4s;
  }

  .my-switch.my-switch-animbg:before {
    transition: left 0.3s;
  }

  .my-switch.my-switch-animbg:checked {
    box-shadow: #dfdfdf 0 0 0 0 inset;
    background-color: #4bd763;
    transition: border-color 0.4s, background-color ease 0.4s;
  }

  .my-switch.my-switch-animbg:checked:before {
    transition: left 0.3s;
  }

  .my-switch.my-switch-anim {
    transition: border cubic-bezier(0, 0, 0, 1) 0.4s,
    box-shadow cubic-bezier(0, 0, 0, 1) 0.4s;
  }

  .my-switch.my-switch-anim:before {
    transition: left 0.3s;
  }

  .my-switch.my-switch-anim:checked {
    box-shadow: #4bd763 0 0 0 16px inset;
    background-color: #4bd763;
    transition: border ease 0.4s, box-shadow ease 0.4s, background-color ease 1.2s;
  }

  .my-switch.my-switch-anim:checked:before {
    transition: left 0.3s;
  }
</style>
